package site.psvm.MyJunit;

import site.psvm.MyJunit.DefineAnnotation.MyAfter;
import site.psvm.MyJunit.DefineAnnotation.MyBefore;
import site.psvm.MyJunit.DefineAnnotation.MyTest;

import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;

public class LoadAnnotation {
    public static void main(String[] args) throws NoSuchMethodException, InvocationTargetException, InstantiationException, IllegalAccessException {
        Class<Demo> demoClass = Demo.class;
        Constructor<Demo> constructor = demoClass.getDeclaredConstructor();
        Demo instance = constructor.newInstance();
        Method[] methods = demoClass.getMethods();

        ArrayList<Method> beforeMethods = new ArrayList<>();
        ArrayList<Method> runMethods = new ArrayList<>();
        ArrayList<Method> afterMethods = new ArrayList<>();

        //遍历注解
        for (Method method : methods) {
            if (method.isAnnotationPresent(MyBefore.class)){
                beforeMethods.add(method);
                continue;
            }
            if (method.isAnnotationPresent(MyTest.class)){
                runMethods.add(method);
                continue;
            }
            if (method.isAnnotationPresent(MyAfter.class)){
                afterMethods.add(method);
            }
        }

        //运行测试方法
        for (Method method : runMethods) {
            //Before
            for (Method beforeMethod : beforeMethods) {
                beforeMethod.invoke(instance);
            }

            //Test
            method.invoke(instance);

            //After
            for (Method afterMethod : afterMethods) {
                afterMethod.invoke(instance);
            }
        }
    }
}
